#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
#include <netdb.h>

const char* get_server_ip();

int main(int agrc,char** argv)
{
    const char* srv_ip = get_server_ip();
    if(srv_ip == NULL)
    {
        fprintf(stderr,"域名解析失败！\n");
        return 1;
    }
    
    int sock = socket(AF_INET, SOCK_STREAM, 0);

    if(-1 == sock)
    {
        perror("socket");
        return 1;
    }


    // 第三步：连接服务器

    // 指定服务器的地址
    struct sockaddr_in srv_addr;
    srv_addr.sin_family = AF_INET;
    srv_addr.sin_addr.s_addr = inet_addr(srv_ip);
    srv_addr.sin_port = htons(80);

    if(-1 == connect(sock, (struct sockaddr*)&srv_addr, sizeof(srv_addr)))
    {
        perror("connect");
        return 1;
    }

    // 第四步：收发数据

    
    char* msg = malloc(5 * 1024 * 1024);
    if(msg == NULL)
    {
        
    }
    int ret;int cnt = 0;
    sprintf(msg,"/GET /weathernew/pc?query=%E6%B9%96%E5%8C%97%E6%AD%A6%E6%B1%89%E5%A4%A9%E6%B0%94&srcid=4982 HTTP/1.1/\r\nConnection: close\r\nHost: weathernew.pae.baidu.com\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36\r\n");
    ret= send(sock,msg,strlen(msg), 0);

    while(ret= recv(sock,msg + cnt,1024, 0) > 0)
    {
        cnt += ret;
    }
    msg[cnt] = '\0';
    printf("%s\n",msg);
    free(msg);
    // 第五步：端开连接
    close(sock);
    
    return 0;
}




//通过域名解析ip地址
const char* get_server_ip()
{
    struct hostent* p = gethostbyname("weathernew.pae.baidu.com");
    
    if(p == NULL)
        return NULL;
    return inet_ntoa(*(struct in_addr*)p->h_addr_list[0]);

}